package com.gimi.cloud.bbp.client.service.bank.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.bbp.client.service.bank.BankService;
import com.gimi.cloud.bbp.common.utils.HttpClientUtil;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.dao.dao.bank.BankDao;
import com.gimi.cloud.bbp.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.bbp.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.bbp.dto.bank.BankDTO;
import com.gimi.cloud.bbp.dto.lianlian.BankCardQueryBean;
import com.gimi.cloud.bbp.dto.lianlian.PayCashBean;
import com.gimi.cloud.bbp.entity.bank.Bank;
import com.gimi.cloud.bbp.entity.userInfo.RdUserInfoEntity;

@Service
@Transactional
public class BankServiceImpl implements BankService {
	private static Logger logger = LoggerFactory.getLogger(BankServiceImpl.class);

	private static String TRADER_MD5_KEY = "201609301001140386_51sudai_20161113";

	private final static String prikeyvalue = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOQOPXytBHHEw535HJKFpcSG6AtGip31pLbFBg+uOZh1W9GZO3ArwifEV6WxhiwMpXAyYg0nB3CYZMxhhVWr1AycXFL6b8CKO5uPSsqHK+MBZcNXkSvuFRit21TXxR+8j8G/km/cyqQRK2m0smdT3/+AjPl1P7LTWEh9VU6SoHnhAgMBAAECgYAf9HrbIGcyBc8fMIu3YDC1E+4pvk2oCoZ08bCCu/foC/G8scrpUchXyCQ73F8fhvobeYPRsflR5pihJr0HHxeMFRWxzPbgSgmQnRD2qMR0QLC2ScWJXACmhm1lfNR9Evx09jXe6LvvEvw+nk0i0tBgIH4eXMXoaMykA68/oxuQvQJBAPch3LnpYXm8J8u0krFfNo2mrZSY2mIQmQvKqPJhrtuyDxl0a7oSZFIcrl2ZXmNDgzwttR21isKb+jrY9Y4tEy8CQQDsPSQwnaRe3akMYxIDQ8Qk4bWnbos17meg1zfV1Vn6RowFErHL1GICmJj61Gy3GB/M/lANtlZg05a0W7/1nT/vAkEAv3tKRfZRY3xpLUnlW29Vmp2p4vgoRVFs9Bj7nIoZbPpi/qsZCRxVBNZaOAWsf6cA2TDlI3bVZAJs+QnAAYBlWwJADlxpJstugpXXAPnEzo4ADn3qHROLQuwLQKvUqRsfLSe8u1I3nLx8eMvuANGJClhdFokfNLYw6hHyx2QMd1Hn4QJAU8XeknO8EA+4VxJKfjKqZumTycNHjSPb4XLbz0OIQMrkDiryZfusd7pzLGUCKcveQW0dywehlyZW3IhMcwjpAw==";


	@Autowired
	private BankDao bankDao;
	@Autowired
	private SysConfigDao sysConfigDao;

	@Override
	public Bank getBankBycardNo(String cardNo) {
		//查询该cardNo是否认证过
		Bank  bank = bankDao.getBankBycardNo(cardNo);
		return bank;
	}

	@Override
	public Bank getBankByUserId(Integer userId) {
		//查询该user是否绑定过银行卡
		Bank  bank = bankDao.getBankByUserIdOrderbcId(userId);
		return bank;
	}

	@Override
	public BankDTO getBankDTOByUserId(Integer userId) {
		//查询该user是否绑定过银行卡
		BankDTO  bank = bankDao.getBankByUserId(userId);
		return bank;
	}

	@Override
	public void insert(Bank bank) {
		bankDao.insert(bank);
	}

	@Override
	public void update(Bank bank) {
		bankDao.updateByPrimaryKey(bank);
	}

	@Override
	public PayCashBean bankCardSign(RdUserInfoEntity rdUserInfo, String cardNo) {

		JSONObject config = JSONObject.parseObject(sysConfigDao.getConfigByKey("interface_lianlian"));
		String oldOidPartner = config.getString("lianlian_old_oid_partner");
		String newOidPartner = config.getString("lianlian_new_oid_partner");
		String lianlian_cardandpay = config.getString("lianlian_cardandpay");
		logger.info("连连oldOidPartner，请求参数：" + oldOidPartner);
		logger.info("连连newOidPartner，请求参数：" + newOidPartner);
		logger.info("连连lianlian_cardandpay，请求参数：" + lianlian_cardandpay);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		// 用于拼装json，返回给前端，前端发送给连连
		PayCashBean reqBean = new PayCashBean();
			/* 基本的请求参数 */
		// reqBean.setVersion("1.1");
		reqBean.setOid_partner(lianlian_cardandpay);
		logger.info("reqBean.setOid_partner():" + lianlian_cardandpay);
		reqBean.setSign_type("RSA");
		if(newOidPartner.equals(lianlian_cardandpay)){
			reqBean.setPlatform(oldOidPartner);
			logger.info("reqBean.setPlatform():" + oldOidPartner);
		}
		reqBean.setUser_id(rdUserInfo.getUserId()+"");
		reqBean.setId_no(rdUserInfo.getCardId());
		reqBean.setAcct_name(rdUserInfo.getRealName());
		reqBean.setCard_no(cardNo);

		// 风控参数列表 用以下方法拼接
		Map<String, Object> map = new HashMap<>();
		map.put("user_info_mercht_userno", rdUserInfo.getUserId() + "");// 用户在商户系统中的标识
		map.put("user_info_mercht_userlogin", rdUserInfo.getMobilePhone());// 用户在商户系统中的登陆名（手机号、邮箱等标识）
		map.put("user_info_mail", rdUserInfo.getEmail());
		map.put("user_info_bind_phone", rdUserInfo.getMobilePhone());// 用户在平台注册绑定手机号
		map.put("user_info_dt_register", sdf.format(rdUserInfo.getAddTime()));// 用户在平台的注册时间YYYYMMDDH24MISS
		map.put("user_info_full_name", rdUserInfo.getRealName());
		map.put("user_info_id_no", rdUserInfo.getCardId());

		String fengkong = JSON.toJSONString(map);

		reqBean.setRisk_item(fengkong);
		reqBean.setSign(genSign(JSON.parseObject(JSON.toJSONString(reqBean))));
		String reqJson = JSON.toJSONString(reqBean);
		// accountcash.setParmjson(reqJson);


		logger.info("签名.............." + genSign(JSON.parseObject(JSON.toJSONString(reqBean))));
		logger.info("json请求.............." + reqJson);
		return reqBean;
	}

	@Override
	public Map<String, String> bankcardQuery(String cardNo) throws Exception{
		//TripartiteAccount bankQuery = Global.getTripartiteAccount("lianlian_bank_query");

		JSONObject  config =JSONObject.parseObject( sysConfigDao.getConfigByKey("lianlianQuery"));
		String oidPartner = config.getString("oidPartner");
		String url = config.getString("url");
		logger.info("银行卡查询oidPartner，请求参数：" + oidPartner);
		logger.info("银行卡查询url，请求参数：" + url);

		logger.info("银行卡查询开始.............");
		BankCardQueryBean query=new BankCardQueryBean();
		query.setCard_no(cardNo);
		query.setOid_partner(oidPartner);//"201709210000943801"
		query.setSign_type("MD5");
		query.setSign(genSign(JSON.parseObject(JSON
				.toJSONString(query))));
		String reqJson = JSON.toJSONString(query);
		logger.info("银行卡查询............."+reqJson);
		String resJson = HttpClientUtil.doRequestPostString(reqJson,url);//"https://queryapi.lianlianpay.com/bankcardbin.htm"
		logger.info("结果报文为:" + resJson);
		JSONObject jsonraw = JSONObject.parseObject(resJson);
//         String[] res=resJson.split(",");
//         logger.info("银行卡查询结果............."+res);
		String bank_code=jsonraw.getString("bank_code");//res[0].substring(14, res[0].length()-1);
		String bank_name=jsonraw.getString("bank_name");//res[1].substring(13, res[1].length()-1);
		String card_type=jsonraw.getString("card_type");//res[2].substring(13, res[2].length()-1);
		Map<String,String> map=new HashMap<String,String>();
		map.put("bank_code", bank_code);
		map.put("bank_name", bank_name);
		map.put("card_type", card_type);//必须2借记卡
		return map;
	}

	@Override
	public boolean useable(String bank_code) {
		QueryParam param = new QueryParam();
		String sql = "select ifnull(bi_id,0) from rd_bank_info where bank_code = '"+bank_code+"' ";
		param.setSql(sql);
		String result = bankDao.useable(param);
		if(StringUtil.isNotBlank(result)){
			return true;
		}
		return false;
	}

	private static String genSign(JSONObject reqObj) {
//		String sign = reqObj.getString("sign");
		String sign_type = reqObj.getString("sign_type");
		// // 生成待签名串
		String sign_src = genSignData(reqObj);
		System.out.println("商户[" + reqObj.getString("oid_partner") + "]待签名原串" + sign_src);
		if ("MD5".equals(sign_type)) {
			sign_src += "&key=" + TRADER_MD5_KEY;
			return signMD5(sign_src);
		}
		if ("RSA".equals(sign_type)) {
			return getSignRSA(sign_src);
		}
		return null;
	}

	private static String signMD5(String signSrc) {

//		try {
//			return Md5Algorithm.getInstance().md5Digest(signSrc.getBytes("utf-8"));
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
			return null;
//		}
	}

	/**
	 * RSA签名验证
	 *
	 * @param
	 * @return
	 */
	public static String getSignRSA(String sign_src) {
//		return TraderRSAUtil.sign(prikeyvalue, sign_src);
		return null;

	}

	/**
	 * 生成待签名串
	 *
	 * @param
	 * @return
	 */
	public static String genSignData(JSONObject jsonObject) {
		StringBuffer content = new StringBuffer();

		// 按照key做首字母升序排列
		List<String> keys = new ArrayList<String>(jsonObject.keySet());
		Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			// sign 和ip_client 不参与签名
			if ("sign".equals(key)) {
				continue;
			}
			String value = (String) jsonObject.getString(key);
			// 空串不参与签名
			if (null == value) {
				continue;
			}
			content.append((i == 0 ? "" : "&") + key + "=" + value);

		}
		String signSrc = content.toString();
		if (signSrc.startsWith("&")) {
			signSrc = signSrc.replaceFirst("&", "");
		}
		return signSrc;
	}
}
